﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using weixin.Models;

namespace weixin.Controllers
{
    /// <summary>
    /// adminController 的摘要说明
    /// </summary>
    public class adminController : IHttpHandler
    {
        private readonly Services.AdminService service = new Services.AdminService();
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            if (context.Request["Action"] == "login")
            {
                string username = context.Request["username"];
                string userpwd = context.Request["userpwd"];
                tb_Admin model = service.Login(username, userpwd);
                if (model != null)
                {
                    HttpCookie cookie = new HttpCookie("token");
                    cookie.Expires = DateTime.Now.AddDays(7);
                    cookie.HttpOnly = true;
                    cookie.Value = model.LoginToken;
                    context.Response.Cookies.Add(cookie);
                    context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(new { sucess = true, info = "", user = new { name = model.loginName, tname = model.loginTName } }));
                    return;
                }
                else
                {
                    context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(new { sucess = false, info = "账号或密码不正确" }));
                    return;
                }
            }

            if (context.Request["Action"] == "check")
            {
                HttpCookie cookie = context.Request.Cookies.Get("token");
                if (cookie == null || string.IsNullOrEmpty(cookie.Value))
                {
                    context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(new { sucess = false, info = "请先登录", tologin = true }));
                    return;
                }
                tb_Admin model = service.GetByToken(cookie.Value);
                if (model == null)
                {
                    context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(new { sucess = false, info = "登陆已失效", tologin = true }));
                    return;
                }
                TimeSpan ts = DateTime.Now - model.loginDate.Value;
                if (ts.Days > 7)
                {
                    context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(new { sucess = false, info = "登陆已失效", tologin = true }));
                    return;
                }
                context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(new { sucess = true, info = "", user = new { name = model.loginName, tname = model.loginTName } }));
                return;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}